<template>
  <el-dialog
    :visible.sync="visible"
    title="上传文件"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-upload
      :action="url"
      :file-list="fileList"
      drag
      multiple
      :before-upload="beforeUploadHandle"
      :on-success="successHandle"
      class="text-center"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">
        只支持{format: "jpg、jpeg、png、gif"}格式文件！
      </div>
    </el-upload>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      url: process.env.VUE_APP_URL + "/sys/oss/upload",
      // url: "https://jsonplaceholder.typicode.com/posts/",
      num: 0,
      fileList: []
    };
  },
  methods: {
    init() {
      this.visible = true;
    },
    // 上传之前
    beforeUploadHandle(file) {
      const isJPG = file.type === "image/jpg";
      const isJPEG = file.type === "image/jpeg";
      const isGIF = file.type === "image/gif";
      const isPNG = file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;
      var isImg = true;
      if (!isJPG && !isJPEG && !isGIF && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG、JPEG、GIF、PNG 格式!");
        isImg = false;
      }
      if (!isLt5M) {
        this.$message.error("上传头像图片大小不能超过 5MB!");
      }
      return isImg && isLt5M;
    },
    successHandle() {
      this.$message({
        type: "success",
        message: "上传成功！"
      });
      this.$emit("refresh");
    }
  }
};
</script>
<style>
.text-center {
  text-align: center;
}
</style>
